using UnityEngine;
using System;
using UnityEngine.Events;

public class CountdownManager : MonoBehaviour
{
    public static CountdownManager Instance { get; private set; }

    public float CurrentTime { get; private set; }
    public bool IsRunning { get; private set; }

    private float totalTime;
    private UnityEvent onCountdownFinished = new UnityEvent();

    private void Awake()
    {
        if (Instance == null)
        {
            Instance = this;
            DontDestroyOnLoad(gameObject);
        }
        else
        {
            Destroy(gameObject);
        }
    }

    private void Update()
    {
        if (IsRunning)
        {
            CurrentTime -= Time.deltaTime;
            if (CurrentTime <= 0)
            {
                CurrentTime = 0;
                Stop();
                onCountdownFinished.Invoke();
            }
        }
    }

    public void StartCountdown(float seconds)
    {
        totalTime = seconds;
        CurrentTime = seconds;
        IsRunning = true;
    }

    public void Pause()
    {
        IsRunning = false;
    }

    public void Resume()
    {
        IsRunning = true;
    }

    public void Stop()
    {
        IsRunning = false;
        CurrentTime = 0;
    }

    public void AddTime(float seconds)
    {
        CurrentTime += seconds;
        if (CurrentTime > totalTime)
        {
            totalTime = CurrentTime;
        }
    }

    public void SubtractTime(float seconds)
    {
        CurrentTime -= seconds;
        if (CurrentTime < 0)
        {
            CurrentTime = 0;
        }
    }

    public void SetOnCountdownFinishedListener(UnityAction listener)
    {
        onCountdownFinished.AddListener(listener);
    }

    public void RemoveOnCountdownFinishedListener(UnityAction listener)
    {
        onCountdownFinished.RemoveListener(listener);
    }

    public string GetFormattedTime()
    {
        int minutes = Mathf.FloorToInt(CurrentTime / 60F);
        int seconds = Mathf.FloorToInt(CurrentTime - minutes * 60);
        return string.Format("{0:00}:{1:00}", minutes, seconds);
    }
}